// pages/categories/categories.js
let utils = require("../../utils/utils.js");
const app = getApp();

Page({

	/**
	 * 页面的初始数据onload
	 */
	data: {
		bannerVideo: [],
		nav: 1,
		currentIndex: 1,
		imgLength: '', //轮播图长度 5-8
		// end 5-8
		scanCode: '',
		slidericonup: '',
		/* 轮播图点击隐藏事件 */
		notice: [],
		scroll: 222,
		autoplay: true,
		/* 轮播图自动切换 */
		interval: 5200,
		/* 切换间隔时间 */
		duration: 1000,
		/* 起始切换时间 */
		circular: true,
		/* 是否采用衔接滑动 */
		vertical: true,
		/* 滑动方向是否为纵向*/
		navIndex: 0,
		/* 菜品类别初始化下标 */
		curIndex: 0,
		toView: "new",
		indicatorDots: true, //5-8
		num: 0,
		totalprice: 0, //产品总价格
		settlementgoods: [], //结算中心所有产品的属性
		emptystatus: false,
		cartcase: true,
		goodslist: [],
		/* 菜品列表保存变量 */
		onlounch: true,
		/* index----- */
		show: true,
		typeindex: 0,
		swiperimgs: [],
		requestOne: 1,
		isPopup: false,
		isShow: true
			/* index-------glass */
			,
		indexData: [],
		deviceCode: '',
		footers: [{
				icon: 'icon-tianchongxing-',
				name: '首页'
			},
			{
				icon: 'icon-dingdan1',
				name: '订单'
			},
			{
				icon: 'icon-wode1',
				name: '我的'
			}
		],
		show: false,
		typeindex: 0,
		swiperimgs: [],
		noticeImg: '/images/noticeicon2.png',
		deviceImg1:'../../assets/nav_img/device-img2.png',
		deviceImg2:'../../assets/nav_img/device-img.png',
		deviceNameCase:false,
		notices: [{}],
		goods_list: [],
		cart: {
			num: 0,
			cartCase: false,
			totalPrice: ''
		},
		paydailogInfo: {
			show: false
		},
		agreement: {
			checked: true,
			statusContent: '',
			parameter: '',
			agreementShow: false,
			agreementIcon: false
		},
		ContentTwoToOne: '首次租用需缴纳押金，待订单完成后押金随时可退，是否支付？',
		ContentTwoToTwo: '您缴纳押金的可租借数量与实际租借数量不符，请重新缴纳押金，重新缴纳押金后，剩余的押金余额将会退还至您的源支付账户，是否继续？',
		ContentTwoToThree: '您的押金余额使用已过半，当前押金余额不足以租用此次订单，请重新缴纳押金，重新缴纳押金后上次的押金余额将会退还至您的源支付账户，是否继续？',
		getpayUrl: '/order/create',
		payUrl: '/order/pay',
		payCompleteUrl: '/order/payComplete',
		popupUrl: '/tiket/pop',
		getpopupUrl: '/tiket/getTicket',
		requestOne: 1,
		isPopup: false,
		isShow: '',
		getpopup: {
			discountPrice: '',
			ticketDesc: '',
			id: ''
		},
		/* dead--data */
		goods_lists: [],
		index_slide: [],
		scanInfo: false,
		popupLastImg: 'popup.png',
		name: '钟海'
	},
	/* 小官-----------------------------------------------------s */

	/* 小官-----------------------------------------------------e */
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		let that = this;
		/* let indexData=wx.getStorageSync('indexData'); */
		let deviceCode = wx.getStorageSync('deviceCode');
		console.log(deviceCode);
		if (!deviceCode) {
			let scanInfo = true;
			this.setData({
				scanInfo,
			});
		};
		that.getopendid() //设置缓存保存个人信息及获取 openid
		this.img();
	},
	img() {
		let popupimg = app.globalData.baseimg + this.data.popupLastImg;
		let cardBgImg = app.globalData.baseimg + this.data.cardBglastImg;
		this.setData({
			popupimg,
			cardBgImg,
		});
	},
	getpopup() {
		let that = this;
		that.data.isShow = wx.getStorageSync('isShow');
		if (!that.data.isShow) {
			that.data.isShow = '0';
		};
		if (that.data.isShow === '0') {
			let indexData = wx.getStorageSync('indexData');
			let userData = indexData.user;
			let _data = {
				url: that.data.popupUrl,
				loading: true,
				methods: 'post',
				nonelist: true,
				data: {
					'userId': userData.userId,
					'type': userData.type,
					'deviceCode': userData.deviceCode
				}
			};
			utils.request.call(_data, (res) => {
				if (res.data.status == 200) {
					that.data.getpopup = res.data.data;
					that.data.isPopup = true;
					that.data.isShow = '1';
					that.setData({
						isPopup: that.data.isPopup,
						getpopup: that.data.getpopup
					});
					wx.setStorageSync('isShow', that.data.isShow);
				} else {
					that.data.isShow = '1';
					wx.setStorageSync('isShow', that.data.isShow);
				};
			});
		};
	},
	closeCoupon() {
		let isPopup = false;
		this.setData({
			isPopup,
		});
	},
	havePopup() {
		let that = this;
		let indexData = wx.getStorageSync('indexData');
		let userData = indexData.user;
		let id = that.data.getpopup.id;
		let _data = {
			url: that.data.getpopupUrl,
			loading: true,
			data: {
				'userId': userData.userId,
				'type': userData.type,
				'id': id
			}
		};
		utils.request.call(_data, (res) => {
			if (res.data.status == 200) {
				utils.tips('优惠券领取成功！');
				let isPopup = false;
				this.setData({
					isPopup,
				});
			};
		});
	},
	/* 登录获取code/openid/userid数据 */
	getopendid(e) {
		let that = this;
		let deviceCode = wx.getStorageSync('deviceCode');
		console.log(deviceCode);
		let loading = deviceCode ? undefined : true;
		let _data = {
			deviceCode: deviceCode,
			loading: loading
		}
		utils._login.call(_data, (res) => {
			if (res.data.status == 501) {
				let userInfo = {
					openid: '',
					nickname: '',
					headimgurl: '',
					sex: '',
					deviceCode: ''
				};
				userInfo.deviceCode = that.data.deviceCode;
				userInfo.openid = res.data.data;
				wx.setStorageSync('userInfo', userInfo);
				if (res.data.status == 501) {
					wx.navigateTo({
						url: '../login/login'
					});
				};
			} else if (res.data.status == 200) {
				that.data.indexData = res.data.data;
				console.log(res.data.data);
				wx.setStorageSync('indexData', res.data.data); /* 首页用户信息保存在缓存中 */
				if (deviceCode) {
					that.pageload();
				};

			} else if (res.data.status == 500) {
				utils.tips('攻城狮正在努力维护中！');
			};
		});
	},
	/* 首页加载数据 */
	pageload() {
		let that = this;
		//let userInfo = wx.getStorageSync('userInfo');
		/* 获取首页数据 */
		let appurl = app.globalData.baseurl;
		let indexData = wx.getStorageSync('indexData');
		console.log(indexData);
		let deviceName=indexData.advert.device.deviceName;
		indexData.advert.carousels.map((val, key) => {
			val.imageUrl = appurl + val.imageUrl;
		});
		indexData.data.map((val, key) => {
			val.image = appurl + val.image;
			val.num = 0;
			val.numisStatus = false;
		});
		let settlementgoods = wx.getStorageSync('settlementgoods');
		if (settlementgoods) {
			that.showdome(indexData.data);
		};
		that.setData({
			index_slide: indexData.advert.carousels,
			notice: indexData.advert.notice,
			goods_list: indexData.data,
			deviceName,
			deviceNameCase:true
		});
		setTimeout(function() {
			that.getpopup();
		}, 2000);
	},
	//公告
	notice(e) {
		let that = this;
		let _url = '/index/query/notice';
		let _data = {
			url: _url,
			methods: 'get',
			data: ''
		}
		utils.request.call(_data, res => {
			if (res.data.status == 200) {
				let notice = res.data.data;
				that.setData({
					notice
				});
			};
		});
	},
	// 公告列表
	noticeList: function(e) {
		let indexData = wx.getStorageSync('indexData');
		let advertData = indexData.advert;
		let noticeList = advertData.notice;
		wx.setStorageSync('noticeList', noticeList);
		wx.navigateTo({
			url: '../noticeList/noticeList'
		})
	},
	addMinusNum: function(e) {
		let that = this;
		let goods_list = that.data.goods_list;
		let status = e.currentTarget.dataset.status;
		let index = e.currentTarget.dataset.index;
		let indexData = wx.getStorageSync('indexData');
		let userData = indexData.user;
		//return false;
		if (status == 'add') { /* 增加产品 */
			if (goods_list[index].num >= goods_list[index].count) {
				utils.tips('此产品数量不足，请选购其他产品！')
				return false;
			};
			let settlementgoods = wx.getStorageSync('settlementgoods');
			let storageNum = 0;
			if (settlementgoods) {
				settlementgoods.map(function(val, key) {
					storageNum += val.num;
				});
			};
			if (storageNum >= userData.maxCount) {
				utils.tips('已超过用户使用最多副数，请合理选择！');
				return false;
			};
			if (goods_list[index].num == 0) {
				goods_list[index].numisStatus = true;
			};
			that.data.cart.cartCase = true;
			goods_list[index].num++;
			that.setData({
				goods_list,
				cart: that.data.cart
			});
			that.storagegoodsinfo(goods_list[index]);
			that.showdome(goods_list);
		} else { /* 减去产品 */
			if (goods_list[index].num == 1) {
				goods_list[index].numisStatus = false;
			};
			goods_list[index].num--;
			this.setData({
				goods_list,
			});
			that.storagegoodsinfo(goods_list[index]);
			that.showdome(goods_list);
		};
	},
	submitOrder: function() {
		this.request_post();
	},
	/*第一次--支付前端传参
	    requestOne 位 false 请求接口是第一个：'/order/create'
	*   requestOne 位 true 请求接口是第二个：'/order/pay'
	*/
	request_post: function() {
		let that = this;
		this.data.requestOne = 1;
		this.common_request_post(function(res) {
			if (res.data.status == 201) {
				//that.data.paydailogInfo.show = true;
				that.data.agreement.agreementShow = true;
				//that.data.agreement.statusContent = that.data.ContentTwoToOne;
				that.setData({
					//paydailogInfo: that.data.paydailogInfo,
					agreement: that.data.agreement,
				});
			} else if (res.data.status == 202) {
				that.data.paydailogInfo.show = true;
				that.data.agreement.statusContent = that.data.ContentTwoToTwo;
				that.setData({
					paydailogInfo: that.data.paydailogInfo,
					agreement: that.data.agreement,
				});
			} else if (res.data.status == 203) {
				that.data.paydailogInfo.show = true;
				that.data.agreement.statusContent = that.data.ContentTwoToThree;
				that.setData({
					paydailogInfo: that.data.paydailogInfo,
					agreement: that.data.agreement,
				});
			} else if (res.data.status == 200) {
				wx.setStorageSync('fetchCodeInfo', res.data.data)
				that.removeItems();
				wx.redirectTo({
					url: '../fetchcode/fetchcode'
				});
			} else {
				utils.tips(res.data.msg);
			};
		});
	},
	/*第二次确认支付--发起支付*/
	confirmPay: function() {
		let that = this;
		if (that.data.agreement.checked == false) {
			//utils.message('');
			return false;
		};
		that.data.paydailogInfo.show = false;
		that.data.agreement.agreementShow = false;
		this.setData({
			paydailogInfo: that.data.paydailogInfo,
			agreement: that.data.agreement
		});
		that.data.requestOne = 2;
		that.common_request_post(function(res) {
			let parameter = res.data.data;
			that.onBridgeReadyArgments(parameter);
		});
	},
	common_request_post: function(success) {
		let that = this;
		let goods_list = wx.getStorageSync('settlementgoods');
		let objectARR = [];
		goods_list.map(function(val, key) {
			let object = {};
			object.id = val.id;
			object.count = val.num;
			objectARR.push(object);
		});
		let indexData = wx.getStorageSync('indexData');
		let userData = indexData.user;
		let count = that.data.cart.totalNum;
		/* ,getpayUrl:'/order/create'           --1
		,   payUrl:'/order/pay',                --2
		    payCompleteUrl:'/order/payComplete',--3*/
		let requestUrl = that.data.requestOne == 1 ? that.data.getpayUrl : (that.data.requestOne == 2 ? that.data.payUrl :
			that.data.payCompleteUrl);
		let _data = {
			url: requestUrl,
			methods: 'post',
			data: JSON.stringify({
				list: objectARR,
				type: userData.type,
				userId: userData.userId,
				count: count,
				deviceCode: userData.deviceCode
			})
		};
		console.log(_data);
		utils.request.call(_data, (res) => {
			success(res);
		});
	},
	/*发起微信支付*/
	onBridgeReadyArgments: function(param) {
		let that = this;
		let wxpay = true;
		wx.setStorageSync('wxpay', wxpay);
		wx.requestPayment({
			timeStamp: param.timeStamp,
			nonceStr: param.nonceStr,
			package: param.package,
			signType: param.signType,
			paySign: param.paySign,
			success: function(res) {
				if (res.errMsg == "requestPayment:ok") { // 调用支付成功
					that.data.requestOne = 3;
					that.common_request_post(function(res) {
						if (res.data.status == 200) {
							let data = res.data.data;
							wx.setStorageSync('fetchCodeInfo', data);
							that.removeItems();
							wx.removeStorageSync('wxpay');
							wx.navigateTo({
								url: '../fetchcode/fetchcode'
							});
						} else {
							utils.tips(res.data.msg);
							wx.removeStorageSync('wxpay');
						};
					});
				} else if (res.errMsg == 'requestPayment:cancel') {
					utils.tips('支付失败！');
					wx.removeStorageSync('wxpay');
					return false;
				};
			},
			fail: function(res) {
				utils.tips('您已取消支付！');
				wx.removeStorageSync('wxpay');
				//fail
			},
			complete: function() {
				//complete
			},



		});
	},
	/* 关闭弹窗 */
	closeAgreementDailog() {
		this.data.paydailogInfo.show = false;
		this.data.agreement.agreementShow = false;
		this.setData({
			paydailogInfo: this.data.paydailogInfo,
			agreement: this.data.agreement
		});
	},
	/* 控制下拉和减号及折扣显示、隐藏 及数据列表数量改变*/
	showdome(goods_list) {
		let settlementgoods = wx.getStorageSync('settlementgoods');
		console.log(settlementgoods);
		let that = this;
		let num = 0;
		if (settlementgoods.length >= goods_list.length) {
			for (let i = 0; i < settlementgoods.length; i++) {
				for (let j = 0; j < goods_list.length; j++) {
					if (settlementgoods[i].id == goods_list[j].id) {
						goods_list[j].numisStatus = settlementgoods[i].numisStatus;
						goods_list[j].num = settlementgoods[i].num;
						num += goods_list[j].num;
					};
				};
			};
		} else {
			for (let i = 0; i < goods_list.length; i++) {
				for (let j = 0; j < settlementgoods.length; j++) {
					if (goods_list[i].id == settlementgoods[j].id) {
						goods_list[i].numisStatus = settlementgoods[j].numisStatus;
						goods_list[i].num = settlementgoods[j].num;
						num += goods_list[i].num;
					};
				};
			};
		};
		that.data.cart.num = num;
		if (settlementgoods.length > 0) {
			that.data.cart.cartCase = true;
			that.setData({
				cart: that.data.cart,
			});
		} else {
			that.data.cart.cartCase = false;
			that.setData({
				cart: that.data.cart,
			});
		};
		that.totalprice();
	},
	/* 加减产品加入购物车函数及删除购物车产品 */
	storagegoodsinfo(currengoodlist) {
		/* 把产品加入结算中心 */
		let that = this;
		if (currengoodlist.num < 1) {
			let settlementgoods = wx.getStorageSync('settlementgoods');
			currengoodlist.numisStatus = false;
			for (var i = 0; i < settlementgoods.length; i++) {
				if (settlementgoods[i].id == currengoodlist.id) {
					settlementgoods.splice(i, 1);
					wx.setStorageSync('settlementgoods', settlementgoods);
					break;
				};
			};
		} else {
			currengoodlist.numisStatus = true;
			let settlementgoods = wx.getStorageSync('settlementgoods');
			if (!settlementgoods) {
				settlementgoods = [];
				settlementgoods.push(currengoodlist);
				wx.setStorageSync('settlementgoods', settlementgoods);
			} else {
				let settlementgoods = wx.getStorageSync('settlementgoods');
				let arrfalse = false;
				for (var i = 0; i < settlementgoods.length; i++) {
					if (settlementgoods[i].id == currengoodlist.id) {
						settlementgoods.splice(i, 1, currengoodlist); /* 替换数组中的相同项 */
						wx.setStorageSync('settlementgoods', settlementgoods);
						arrfalse = true;
						break;
					};
				};
				if (arrfalse == false) {
					settlementgoods.push(currengoodlist);
					wx.setStorageSync('settlementgoods', settlementgoods);
				};
			};
		};
		/* 计算总价 */
		that.totalprice();
	},
	/* 计算总价及渲染购物车数据 */
	/* 计算总价 */
	totalprice(e) {
		let that = this;
		let settlementgoods = wx.getStorageSync('settlementgoods');
		let ruleData = this.data.indexData.rule;
		let userData = this.data.indexData.user;
		let totalNum = 0; /*用户选择眼镜副数*/
		let totalPrice = 0;
		for (let i = 0; i < settlementgoods.length; i++) {
			totalNum += settlementgoods[i].num;
		};
		that.data.cart.totalNum = totalNum;
		if (ruleData.length > 0) {
			ruleData.map(function(val, key) {
				if (Number(totalNum) <= Number(userData.count)) {
					if (Number(val.count) === Number(Number(totalNum) - Number(userData.count))) {
						//console.log(val.)
						if (Number(val.priceStatus) === 1) {
							totalPrice = val.discountPrice;
						} else {
							totalPrice = val.price;
						};
					};
				} else {
					if (Number(val.count) === Number(totalNum)) {
						//console.log(val.)
						if (Number(val.priceStatus) === 1) {
							totalPrice = val.discountPrice;
						} else {
							totalPrice = val.price;
						};
					};
				};
			});
		};
		that.data.cart.totalPrice = Number(totalPrice).toFixed(2);
		that.setData({
			cart: that.data.cart
		})
	},
	removeItems: function() {
		wx.removeStorageSync('settlementgoods');
		this.totalprice();
		this.data.cart.cartCase = false;
		this.setData({
			cart: this.data.cart,
		});
	},
	pageLinks: function(e) {
		let index = e.currentTarget.dataset.index;
		if (index == 0) {
			return false;
		} else if (index == 1) {
			wx.reLaunch({
				url: '../myorder/myorder'
			});
		} else {
			wx.reLaunch({
				url: '../mine/mine'
			});
		};
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		let deviceCode = wx.getStorageSync('deviceCode');
		if (!deviceCode) {
			const scene = decodeURIComponent(options.scene);
			console.log(typeof scene);
			console.log(scene);
			if(scene=='undefined'){
				deviceCode = '';
			}else{
				let index=scene.lastIndexOf(':');
				deviceCode=scene.substr(index+1,scene.length);
			};
			wx.setStorageSync('deviceCode', deviceCode);
		};
	},
	getScancode() {
		var _this = this;
		// 允许从相机和相册扫码
		let wxpay = true;
		wx.setStorageSync('wxpay', wxpay);
		wx.scanCode({
			success: (res) => {
				if (res.errMsg === "scanCode:ok") {
					let path = res.path || res.result;
					//let index = path.lastIndexOf('%3D');
					let deviceCode = path.substr(path.length - 8, path.length);
					wx.setStorageSync('deviceCode', deviceCode);
					_this.getopendid();
					let scanInfo = false;
					_this.setData({
						scanInfo,
					});
					wx.removeStorageSync('wxpay');
				};
			},
			fail: (res) => {
				utils.tips("请扫描正确的影院设备二维码！");
				wx.removeStorageSync('wxpay');
			}
		});
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},
	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},
	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},
	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	}
})
